import React, { useState, useEffect } from 'react';
import { Space, Button, Card, Empty, Modal, Input, Select, message } from 'antd';
import { 
  PlusOutlined, CheckSquareOutlined, CheckCircleOutlined, 
  FileTextOutlined, FormOutlined, AppstoreOutlined,
  DeleteOutlined, EditOutlined, CopyOutlined, ArrowUpOutlined, ArrowDownOutlined
} from '@ant-design/icons';
import { Question, QuestionType, Paper, QuestionBank } from '@/types/question';
import { questionService } from '@/services/questionService';
import QuestionDisplay from './components/QuestionDisplay';
import QuestionEditModal from './components/QuestionEditModal';
import QuestionSelector from '../components/QuestionSelector';
import styles from './QuestionEditPanel.module.css';

const { Option } = Select;

interface QuestionEditPanelProps {
  questions: Question[];
  onChange: (questions: Question[]) => void;
  paper?: Partial<Paper>;
  onPaperChange?: (paper: Partial<Paper>) => void;
}

const QuestionEditPanel: React.FC<QuestionEditPanelProps> = ({ questions, onChange, paper, onPaperChange }) => {
  const [editingQuestion, setEditingQuestion] = useState<Question | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [selectorVisible, setSelectorVisible] = useState(false);
  const [paperTitle, setPaperTitle] = useState(paper?.title || '');
  const [questionBanks, setQuestionBanks] = useState<QuestionBank[]>([]);
  const [loadingBanks, setLoadingBanks] = useState(false);
  const [selectedBankId, setSelectedBankId] = useState<number | undefined>();

  // 加载题库列表
  useEffect(() => {
    loadQuestionBanks();
  }, []);

  // 从URL参数或paper设置默认题库
  useEffect(() => {
    if (selectedBankId === undefined) {
      // 先检查URL参数
      const urlParams = new URLSearchParams(window.location.search);
      const defaultBank = urlParams.get('defaultBank');
      if (defaultBank) {
        setSelectedBankId(Number(defaultBank));
        return;
      }
      
      // 再检查是否有已有题目
      if (questions.length > 0) {
        const firstQuestion = questions[0];
        if (firstQuestion.question_bank) {
          setSelectedBankId(firstQuestion.question_bank);
        }
      }
    }
  }, [questions]);

  const loadQuestionBanks = async () => {
    setLoadingBanks(true);
    try {
      const response = await questionService.getQuestionBanks({ page: 1, limit: 100 });
      const data = response.data.data;
      setQuestionBanks(data.results);
      
      // 如果有已有题目，设置第一个题目的题库为默认
      if (questions.length > 0 && data.results.length > 0) {
        const firstQuestion = questions[0];
        if (firstQuestion.question_bank) {
          setSelectedBankId(firstQuestion.question_bank);
        }
      }
    } catch (error) {
      message.error('加载题库列表失败');
    } finally {
      setLoadingBanks(false);
    }
  };

  // 添加新题目（创建）
  const handleAddQuestion = (type: QuestionType) => {
    const newQuestion: Question = {
      title: '',
      content: '',
      type,
      question_bank: selectedBankId,
      difficulty: 2,
      tags: [],
      choices: type === QuestionType.TRUE_FALSE
        ? [{ key: 'A', content: '正确' }, { key: 'B', content: '错误' }]
        : type === QuestionType.FILL_BLANK
        ? []
        : [
            { key: 'A', content: '' },
            { key: 'B', content: '' },
            { key: 'C', content: '' },
            { key: 'D', content: '' },
          ],
      correct_answers: [],
      has_code: false,
      code_content: '',
      code_language: 'cpp',
      answer_explanation: '',
      hint: '',
      is_active: true,
      _score: 10,
      _group_name: '',
      _is_required: true,
    } as any;

    setEditingQuestion(newQuestion);
    setEditModalVisible(true);
  };

  // 从题库添加题目
  const handleAddFromBank = async (selectedQuestions: any[]) => {
    const newQuestions = selectedQuestions.map(q => ({
      ...q,
      _score: 10,
      _group_name: '',
      _is_required: true,
    }));
    const updatedQuestions = [...questions, ...newQuestions];
    onChange(updatedQuestions);
    setSelectorVisible(false);
    // 更新试卷关联
    await updatePaperQuestions(updatedQuestions);
  };

  // 编辑题目
  const handleEdit = (index: number) => {
    setEditingQuestion(questions[index]);
    setEditModalVisible(true);
  };

  // 保存编辑后的题目
  const handleSaveQuestion = async (question: Question) => {
    try {
      if (editingQuestion && (editingQuestion as any).id) {
        // 更新现有题目
        const response = await questionService.updateQuestion((editingQuestion as any).id, {
          title: question.title,
          content: question.content,
          type: question.type,
          question_bank: question.question_bank,
          difficulty: question.difficulty,
          tags: question.tags || [],
          choices: question.choices || [],
          correct_answers: question.correct_answers || [],
          blank_count: question.blank_count || 0,
          case_sensitive: question.case_sensitive || false,
          has_code: question.has_code || false,
          code_content: question.code_content || '',
          code_language: question.code_language || '',
          answer_explanation: question.answer_explanation || '',
          hint: question.hint || '',
          is_active: question.is_active !== false,
          source: question.source || '',
        } as any);
        
        const index = questions.findIndex(q => q.id === editingQuestion.id);
        if (index !== -1) {
          const newQuestions = [...questions];
          newQuestions[index] = { ...response.data.data, ...{ 
            _score: (questions[index] as any)._score,
            _group_name: (questions[index] as any)._group_name,
            _is_required: (questions[index] as any)._is_required,
          }};
          onChange(newQuestions);
          
          // 更新试卷关联
          await updatePaperQuestions(newQuestions);
        }
        message.success('题目更新成功');
      } else {
        // 添加新题目
        const response = await questionService.createQuestion({
          title: question.title,
          content: question.content,
          type: question.type,
          question_bank: question.question_bank || selectedBankId,
          difficulty: question.difficulty,
          tags: question.tags || [],
          choices: question.choices || [],
          correct_answers: question.correct_answers || [],
          blank_count: question.blank_count || 0,
          case_sensitive: question.case_sensitive || false,
          has_code: question.has_code || false,
          code_content: question.code_content || '',
          code_language: question.code_language || '',
          answer_explanation: question.answer_explanation || '',
          hint: question.hint || '',
          is_active: question.is_active !== false,
          source: question.source || '',
        } as any);
        
        const newQuestions = [...questions, { ...response.data.data, _score: 10, _group_name: '', _is_required: true }];
        onChange(newQuestions);
        
        // 更新试卷关联
        await updatePaperQuestions(newQuestions);
        
        message.success('题目创建成功');
      }
      setEditModalVisible(false);
    } catch (error: any) {
      message.error(error.response?.data?.message || '保存题目失败');
    }
  };

  // 更新试卷题目关联
  const updatePaperQuestions = async (newQuestions: Question[]) => {
    if (!paper?.id) return;
    
    try {
      const questionsData = newQuestions.map((q, index) => ({
        question_id: q.id!,
        sequence: index + 1,
        group_name: (q as any)._group_name || '',
        score: (q as any)._score || 10,
        is_required: (q as any)._is_required !== false,
      }));

      const totalScore = questionsData.reduce((sum, q) => sum + q.score, 0);

      await questionService.updatePaper(paper.id, {
        total_score: totalScore,
        questions_data: questionsData,
      } as any);
    } catch (error) {
      console.error('更新试卷关联失败:', error);
    }
  };

  // 删除题目
  const handleDelete = async (index: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这道题目吗？',
      async onOk() {
        const newQuestions = questions.filter((_, i) => i !== index);
        onChange(newQuestions);
        // 更新试卷关联
        await updatePaperQuestions(newQuestions);
      },
    });
  };

  // 复制题目
  const handleCopy = (index: number) => {
    const copied = { ...questions[index] };
    delete (copied as any).id;  // 移除ID，作为新题目
    onChange([...questions.slice(0, index + 1), copied, ...questions.slice(index + 1)]);
  };

  // 上移
  const handleMoveUp = async (index: number) => {
    if (index === 0) return;
    const newQuestions = [...questions];
    [newQuestions[index - 1], newQuestions[index]] = [newQuestions[index], newQuestions[index - 1]];
    onChange(newQuestions);
    // 更新试卷关联
    await updatePaperQuestions(newQuestions);
  };

  // 下移
  const handleMoveDown = async (index: number) => {
    if (index === questions.length - 1) return;
    const newQuestions = [...questions];
    [newQuestions[index], newQuestions[index + 1]] = [newQuestions[index + 1], newQuestions[index]];
    onChange(newQuestions);
    // 更新试卷关联
    await updatePaperQuestions(newQuestions);
  };

  // 更新题目配置（分数、分组等）
  const handleUpdateConfig = async (index: number, key: string, value: any) => {
    const newQuestions = [...questions];
    (newQuestions[index] as any)[key] = value;
    onChange(newQuestions);
    // 更新试卷关联
    await updatePaperQuestions(newQuestions);
  };

  return (
    <div className={styles.panel}>
      {/* 左侧：题型选择面板 */}
      <div className={styles.sidebar}>
        <Card title="添加题目" size="small" className={styles.addCard}>
          <Space direction="vertical" style={{ width: '100%' }}>
            <Button
              block
              icon={<CheckCircleOutlined />}
              onClick={() => handleAddQuestion(QuestionType.SINGLE_CHOICE)}
            >
              单选题
            </Button>
            <Button
              block
              icon={<CheckSquareOutlined />}
              onClick={() => handleAddQuestion(QuestionType.MULTIPLE_CHOICE)}
            >
              多选题
            </Button>
            <Button
              block
              icon={<CheckCircleOutlined />}
              onClick={() => handleAddQuestion(QuestionType.TRUE_FALSE)}
            >
              判断题
            </Button>
            <Button
              block
              icon={<FormOutlined />}
              onClick={() => handleAddQuestion(QuestionType.FILL_BLANK)}
            >
              填空题
            </Button>
            <Button
              block
              icon={<AppstoreOutlined />}
              onClick={() => handleAddQuestion(QuestionType.COMPOSITE)}
            >
              综合题
            </Button>
            <Button
              block
              type="dashed"
              icon={<FileTextOutlined />}
              onClick={() => setSelectorVisible(true)}
            >
              从题库选择
            </Button>
          </Space>
        </Card>

        <Card title="试卷标题" size="small" className={styles.titleCard}>
          <Input
            value={paperTitle}
            onChange={(e) => setPaperTitle(e.target.value)}
            placeholder="请输入试卷标题"
            onBlur={() => {
              if (paperTitle.trim() && onPaperChange && paper) {
                onPaperChange({ ...paper, title: paperTitle });
              }
            }}
          />
        </Card>

        <Card title="默认题库" size="small" className={styles.titleCard}>
          <Select
            value={selectedBankId}
            onChange={(value) => setSelectedBankId(value)}
            placeholder="选择题库（新建题目将使用此题库）"
            allowClear
            style={{ width: '100%' }}
            loading={loadingBanks}
          >
            {questionBanks.map(bank => (
              <Option key={bank.id} value={bank.id}>
                {bank.name}
              </Option>
            ))}
          </Select>
          <div style={{ marginTop: 8, fontSize: 12, color: '#999' }}>
            在此试卷新建题目时将自动关联到此题库
          </div>
        </Card>
      </div>

      {/* 右侧：题目列表 */}
      <div className={styles.mainArea}>
        {questions.length === 0 ? (
          <Empty
            description="还没有添加题目，请从左侧选择题型添加"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            className={styles.empty}
          />
        ) : (
          <Space direction="vertical" size="middle" style={{ width: '100%' }}>
            {questions.map((question, index) => (
              <Card
                key={index}
                className={styles.questionCard}
                title={
                  <Space>
                    <span>第 {index + 1} 题</span>
                    <span style={{ color: '#666', fontWeight: 'normal' }}>
                      {question.type_display || getTypeDisplay(question.type)}
                    </span>
                  </Space>
                }
                extra={
                  <Space size="small">
                    <Button
                      type="text"
                      size="small"
                      icon={<ArrowUpOutlined />}
                      onClick={() => handleMoveUp(index)}
                      disabled={index === 0}
                    />
                    <Button
                      type="text"
                      size="small"
                      icon={<ArrowDownOutlined />}
                      onClick={() => handleMoveDown(index)}
                      disabled={index === questions.length - 1}
                    />
                    <Button
                      type="text"
                      size="small"
                      icon={<EditOutlined />}
                      onClick={() => handleEdit(index)}
                    />
                    <Button
                      type="text"
                      size="small"
                      icon={<CopyOutlined />}
                      onClick={() => handleCopy(index)}
                    />
                    <Button
                      type="text"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => handleDelete(index)}
                    />
                  </Space>
                }
              >
                <QuestionDisplay 
                  question={question}
                  index={index}
                  onUpdateConfig={(key, value) => handleUpdateConfig(index, key, value)}
                />
              </Card>
            ))}
          </Space>
        )}
      </div>

      {/* 题目编辑模态框 */}
      <Modal
        title={editingQuestion?.id ? '编辑题目' : '新建题目'}
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        footer={null}
        width={900}
        destroyOnClose
      >
        {editingQuestion && (
          <QuestionEditModal
            question={editingQuestion}
            onSave={handleSaveQuestion}
            onCancel={() => setEditModalVisible(false)}
          />
        )}
      </Modal>

      {/* 题库选择器 */}
      <Modal
        title="从题库选择题目"
        open={selectorVisible}
        onCancel={() => setSelectorVisible(false)}
        footer={null}
        width={1000}
      >
        <QuestionSelector
          onSelect={handleAddFromBank}
          excludeIds={questions.filter(q => q.id).map(q => q.id!)}
        />
      </Modal>
    </div>
  );
};

// 题型显示名称
const getTypeDisplay = (type: QuestionType): string => {
  const typeMap = {
    [QuestionType.SINGLE_CHOICE]: '单选题',
    [QuestionType.MULTIPLE_CHOICE]: '多选题',
    [QuestionType.TRUE_FALSE]: '判断题',
    [QuestionType.FILL_BLANK]: '填空题',
    [QuestionType.COMPOSITE]: '综合题',
  };
  return typeMap[type] || type;
};

export default QuestionEditPanel;

